import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ApiResponse, PaginatedResponse } from '@/types/api'

export interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  align?: 'left' | 'center' | 'right'
  sortable?: boolean
  formatter?: (row: any, column: any, cellValue: any) => string
}

export interface UseTableOptions<T> {
  immediate?: boolean
  pageSize?: number
  searchFields?: string[]
  sortField?: string
  sortOrder?: 'asc' | 'desc'
  onSelectionChange?: (selection: T[]) => void
}

export interface TableActions<T> {
  refresh: () => Promise<void>
  search: (query: string) => void
  resetSearch: () => void
  changePage: (page: number) => void
  changePageSize: (size: number) => void
  deleteItem: (id: string | number) => Promise<void>
  batchDelete: (ids: (string | number)[]) => Promise<void>
  exportData: () => void
}

export function useTable<T extends Record<string, any>>(
  fetchFn: (params: any) => Promise<PaginatedResponse<T>>,
  deleteFn?: (id: string | number) => Promise<ApiResponse<any>>,
  options: UseTableOptions<T> = {}
) {
  const {
    immediate = true,
    pageSize = 10,
    searchFields = [],
    sortField,
    sortOrder = 'desc',
    onSelectionChange
  } = options

  // 响应式数据
  const data = ref<T[]>([])
  const loading = ref(false)
  const selection = ref<T[]>([])
  
  // 分页数据
  const pagination = reactive({
    page: 1,
    pageSize,
    total: 0,
    totalPages: 0
  })

  // 搜索和排序
  const searchQuery = ref('')
  const sortConfig = reactive({
    field: sortField || '',
    order: sortOrder
  })

  // 计算属性
  const hasSelection = computed(() => selection.value.length > 0)
  const selectedIds = computed(() => 
    selection.value.map(item => item.id).filter(Boolean)
  )

  // 获取数据
  const fetchData = async (showLoading = true) => {
    if (showLoading) loading.value = true
    
    try {
      const params = {
        page: pagination.page,
        page_size: pagination.pageSize,
        search: searchQuery.value,
        ordering: sortConfig.field ? 
          `${sortConfig.order === 'desc' ? '-' : ''}${sortConfig.field}` : undefined
      }

      const response = await fetchFn(params)
      
      if (response.success && response.data) {
        data.value = response.data.results || []
        pagination.total = response.data.pagination?.total || 0
        pagination.totalPages = response.data.pagination?.total_pages || 0
      } else {
        throw new Error(response.message || '获取数据失败')
      }
    } catch (error: any) {
      ElMessage.error(error.message || '获取数据失败')
      data.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 刷新数据
  const refresh = async () => {
    await fetchData()
  }

  // 搜索
  const search = (query: string) => {
    searchQuery.value = query
    pagination.page = 1
    fetchData()
  }

  // 重置搜索
  const resetSearch = () => {
    searchQuery.value = ''
    pagination.page = 1
    fetchData()
  }

  // 分页操作
  const changePage = (page: number) => {
    pagination.page = page
    fetchData()
  }

  const changePageSize = (size: number) => {
    pagination.pageSize = size
    pagination.page = 1
    fetchData()
  }

  // 排序操作
  const handleSort = (column: any) => {
    if (column.prop) {
      sortConfig.field = column.prop
      sortConfig.order = column.order === 'ascending' ? 'asc' : 'desc'
      pagination.page = 1
      fetchData()
    }
  }

  // 选择操作
  const handleSelectionChange = (newSelection: T[]) => {
    selection.value = newSelection
    onSelectionChange?.(newSelection)
  }

  // 删除单个项目
  const deleteItem = async (id: string | number) => {
    if (!deleteFn) {
      ElMessage.error('删除功能未配置')
      return
    }

    try {
      await ElMessageBox.confirm('确定要删除这个项目吗？', '确认删除', {
        type: 'warning'
      })

      const response = await deleteFn(id)
      
      if (response.success) {
        ElMessage.success(response.message || '删除成功')
        await refresh()
      } else {
        throw new Error(response.message || '删除失败')
      }
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '删除失败')
      }
    }
  }

  // 批量删除
  const batchDelete = async (ids?: (string | number)[]) => {
    if (!deleteFn) {
      ElMessage.error('删除功能未配置')
      return
    }

    const deleteIds = ids || selectedIds.value
    if (deleteIds.length === 0) {
      ElMessage.warning('请选择要删除的项目')
      return
    }

    try {
      await ElMessageBox.confirm(
        `确定要删除选中的 ${deleteIds.length} 个项目吗？`,
        '确认批量删除',
        { type: 'warning' }
      )

      // 这里需要根据实际API设计调整
      for (const id of deleteIds) {
        await deleteFn(id)
      }

      ElMessage.success('批量删除成功')
      await refresh()
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '批量删除失败')
      }
    }
  }

  // 导出数据
  const exportData = () => {
    // 这里可以实现数据导出逻辑
    ElMessage.info('导出功能开发中...')
  }

  // 初始化
  if (immediate) {
    onMounted(() => {
      fetchData()
    })
  }

  const actions: TableActions<T> = {
    refresh,
    search,
    resetSearch,
    changePage,
    changePageSize,
    deleteItem,
    batchDelete,
    exportData
  }

  return {
    data,
    loading,
    selection,
    pagination,
    searchQuery,
    sortConfig,
    hasSelection,
    selectedIds,
    fetchData,
    handleSort,
    handleSelectionChange,
    actions
  }
}
